package com.yueqian.framework.config;


import static com.yueqian.framework.enmus.ExceptionEnum.USER_PASSWORD_ERROR;

import javax.annotation.Resource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.yueqian.framework.exception.GlobalException;
import com.yueqian.system.service.impl.UserServiceImpl;

@Configuration
public class ApplicationConfig {


	@Resource
	private UserServiceImpl userService;

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	@Bean
	public AuthenticationProvider authenticationProvider() {
		return new AuthenticationProvider() {
			@Override
			public Authentication authenticate(Authentication authentication) throws AuthenticationException {
				String username = authentication.getPrincipal().toString();
				String password = authentication.getCredentials().toString();
				UserDetails userDetails = userService.loadUserByUsername(username);
				BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
				password = bCryptPasswordEncoder.encode(password);
				if (bCryptPasswordEncoder.matches(password, userDetails.getPassword())) {
					throw new GlobalException(USER_PASSWORD_ERROR);
				}
				return new UsernamePasswordAuthenticationToken(username, password, null);
			}

			@Override
			public boolean supports(Class<?> authentication) {
				return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
			}
		};
//		DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
//		authProvider.setUserDetailsService(userService);
//		authProvider.setPasswordEncoder(passwordEncoder());
//		return authProvider;
	}

	@Bean
	public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
		return config.getAuthenticationManager();
	}
}
